<?php
/**
 * Created by 登陆类.
 * User: 尚金殿
 * Date: 2018/8/20
 * Time: 14:32
 */

namespace app\admin\controller;


use think\Controller;
use think\Db;
use think\Request;

class LoginController extends Controller
{
    //加载登陆页
    public function lists(){
        if(session('TourAdminUser')){
            $this->redirect('/admin.php');
        }
            return $this->fetch();
    }

    //登陆操作
    public function checkLogin(Request $request){
        //获取数据
        $username = $request->param('username');
        $password = $request->param('password');
        $code = $request->param('verfiy');

        //验证数据
        if(!trim($username)){
            return show(0,'用户名不能为空');
        }
        if(!trim($password)){
            return show(0,'密码不能为空');
        }

        if(!check_verify($code)){
            return show(0,'验证码输入错误');
        }

        //根据用户名入库查询
        $user = Db::name('admin')->where(['username'=>$username,'admin_status'=>1])->find();

        if(!$user || !is_array($user)){
            return show(0,'用户名错误，请重新输入');
        }

        //判定密码
        if(getMD5Password($password) != $user['password']){
            return show(0,'密码错误');
        }

        //更新数据库
        $data['last_login_ip'] = $request->ip();
        $data['last_login_time'] = time();

        $res = Db::name('admin')->where('admin_id',$user['admin_id'])->update($data);

        //将数据库存入session
        if($res) {
            unset($user['password']);
            session('TourAdminUser', $user);
            return show(1,'登陆成功');
        }else{
            return show(0,'登陆失败');
        }
    }

    //退出登陆
    public function loginOut(){
        session('TourAdminUser',null);
        $this->redirect('/admin.php');
    }
}